package com.hopu.petshop.service.impl;

import com.hopu.petshop.dao.PetDAO;
import com.hopu.petshop.entity.PageEntity;
import com.hopu.petshop.entity.Pet;
import com.hopu.petshop.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

/**
 * PetService的实现
 */
@Service
public class PetServiceImpl implements PetService {

    //依赖注入 自动装配dao实现对象
    @Autowired
    private PetDAO petDAO;

    @Override
    public List<Pet> findAllPets() throws SQLException {
        return petDAO.selectAllPets();
    }

    @Override
    public void addPet(Pet pet) throws SQLException {
        petDAO.insertPet(pet);
    }

    @Override
    public void modifyPetById(Pet pet) throws SQLException {
        petDAO.updatePetById(pet);
    }

    @Override
    public Pet findPetById(int id) throws SQLException {
        return petDAO.selectPetById(id);
    }

    @Override
    public void removePetById(int id) throws SQLException {
        petDAO.deletePetById(id);
    }

    @Override
    public List<Pet> findPetByName(String name) throws SQLException {
        return petDAO.selectPetByName(name);
    }

    @Override
    public PageEntity<Pet> findPetsPage(int current) throws SQLException {
        //查询宠物的总数
        int count = petDAO.selectPetsCount();
        //计算总页数
        int pageCount = count % PageEntity.PAGE_SIZE == 0 ? count / PageEntity.PAGE_SIZE : count / PageEntity.PAGE_SIZE + 1;
        //分页查询宠物
        List<Pet> pets = petDAO.selectPetsLimit((current - 1) * PageEntity.PAGE_SIZE,PageEntity.PAGE_SIZE);
        //包装到分页对象中
        PageEntity<Pet> page = new PageEntity<>();
        page.setCurrent(current);
        page.setData(pets);
        page.setPageCount(pageCount);
        return page;
    }


}
